package com.jmhy.sdk.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jmhy.sdk.common.JiMiSDK;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.http.ApiAsyncTask;
import com.jmhy.sdk.http.ApiRequestListener;
import com.jmhy.sdk.model.Guest;
import com.jmhy.sdk.model.Registermsg;
import com.jmhy.sdk.sdk.JmhyApi;
import com.jmhy.sdk.utils.FragmentUtils;
import com.jmhy.sdk.utils.Utils;

public class JmUserRegisterFragment8 extends JmBaseFragment implements View.OnClickListener {

    private Button btn_reback, btn_register;
    private EditText et_input_account, et_input_pwd;
    private ImageView iv_down_eye_btn;
    private TextView tv_register_account;
    private ApiAsyncTask mRegisterTask;
    private boolean isShowPwd = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        view = inflater.inflate(AppConfig.resourceId(getActivity(),
                "jm_account_register_8", "layout"), container, false);
        view.setClickable(true);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {

        btn_reback = getView().findViewById(AppConfig.resourceId(getActivity(), "btn_reback", "id"));
        btn_reback.setOnClickListener(this);

        btn_register = getView().findViewById(AppConfig.resourceId(getActivity(), "btn_register", "id"));
        btn_register.setOnClickListener(this);

        et_input_account = getView().findViewById(AppConfig.resourceId(getActivity(), "et_input_account", "id"));


        et_input_pwd = getView().findViewById(AppConfig.resourceId(getActivity(), "et_input_pwd", "id"));
        et_input_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());


        iv_down_eye_btn = getView().findViewById(AppConfig.resourceId(getActivity(), "iv_down_eye_btn", "id"));
        iv_down_eye_btn.setOnClickListener(this);

        tv_register_account = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_register_account", "id"));
        tv_register_account.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == AppConfig.resourceId(getActivity(), "btn_reback", "id")) {
            Fragment selectAccountLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_LOGIN_TAG);
            replaceFragmentToActivity(getFragmentManager(), selectAccountLoginFragment, AppConfig.resourceId(getActivity(), "content", "id"));
        } else if (id == AppConfig.resourceId(getActivity(), "btn_register", "id")) {
            startRegister();
        } else if (id == AppConfig.resourceId(getActivity(), "iv_down_eye_btn", "id")) {
            if (!isShowPwd) {
                isShowPwd = true;
                et_input_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                iv_down_eye_btn.setImageResource(AppConfig.resourceId(getActivity(), "jm_open_eye", "drawable"));
            } else {
                isShowPwd = false;
                et_input_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                iv_down_eye_btn.setImageResource(AppConfig.resourceId(getActivity(), "jm_close_eye", "drawable"));
            }

        } else if (id == AppConfig.resourceId(getActivity(), "tv_register_account", "id")) {
            turnToIntent(AppConfig.USERAGREEMENTURL);
        }
    }

    private void startRegister() {
        String user = et_input_account.getText().toString().trim();
        String password = et_input_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(user)) {
            showMsg(AppConfig.getString(getActivity(), "user_hintuser_msg"));
            return;
        }
        if (TextUtils.isEmpty(password)) {
            showMsg(AppConfig.getString(getActivity(), "user_edit_pwdhint"));
            return;
        }
        getRegister(user, password);
    }

    /**
     * 注册
     *
     * @param username 账号 或手机号
     * @param password 密码
     */
    public void getRegister(final String username, final String password) {
        mRegisterTask = JmhyApi.get().startRegister(getActivity(), AppConfig.appKey, username, password, new ApiRequestListener() {

            @Override
            public void onSuccess(Object obj) {
                // TODO Auto-generated method stub
                if (obj != null) {
                    Registermsg registermsg = (Registermsg) obj;
                    if (registermsg.getCode().equals("0")) {

                        mSeference.saveAccount(username, "~~test", registermsg.getAuto_login_token());
                        AppConfig.saveMap(username, "~~test", registermsg.getAuto_login_token());
                        sendData(AppConfig.REGISTER_SUCCESS, obj, handler);

                    } else {
                        sendData(AppConfig.FLAG_FAIL, registermsg.getMessage(), handler);
                        JiMiSDK.reportRequestErrorAction(getActivity(), "sdk_account_register_error", registermsg.getCode(), registermsg.getMessage());
                    }
                } else {
                    sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
                }
            }

            @Override
            public void onError(int statusCode) {
                // TODO Auto-generated method stub
                sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
            }
        });
    }


    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            switch (msg.what) {
                case AppConfig.FLAG_FAIL:
                    String resultmsg = (String) msg.obj;
                    showMsg(resultmsg);
                    break;
                case AppConfig.REGISTER_SUCCESS:
                    Registermsg registermsg = (Registermsg) msg.obj;

                    JiMiSDK.getStatisticsSDK().onRegister("JiMiSDK", true);

                    toAutologin(registermsg);

                    getActivity().finish();

                    break;
                case AppConfig.GUEST_lOGIN_SUCCESS:
                    Guest guest = (Guest) msg.obj;
                    String murl = Utils.toBase64url(guest.getShow_url_after_login());
                    if (TextUtils.isEmpty(murl)) {
                        murl = Utils.toBase64url(guest.getShow_url_popup());
                    }

                    JiMiSDK.getStatisticsSDK().onRegister("JiMiSDK", true);

                    if (!TextUtils.isEmpty(guest.getUpass())) {

                        Bundle args = new Bundle();
                        // Log.i("kk",mobileUser.getMoblie())
                        args.putString("username", guest.getUname());
                        args.putString("upass", guest.getUpass());
                        args.putString("msg", guest.getMessage());
                        args.putString("gametoken", guest.getGame_token());
                        args.putString("openid", guest.getOpenid());
                        args.putString("url", murl);
                        Fragment mJmSetUserFragment = FragmentUtils.getJmSetUserFragment(getActivity(), args);
                        replaceFragmentToActivity(getFragmentManager(), mJmSetUserFragment, AppConfig.resourceId(getActivity(), "content", "id"));
                    } else {
                        wrapaLoginInfo("success", guest.getMessage(), guest.getUname(), guest.getOpenid(), guest.getGame_token());

                        turnToNotice(murl);
                        getActivity().finish();
                    }
                    break;
            }

        }
    };

    @Override
    public void onDestroy() {

        if (mRegisterTask != null) {
            mRegisterTask.cancel(false);
        }

        super.onDestroy();
    }
}
